// pages/register/register.js
import { reqRegisterUserData } from '../../api/register'

Page({
  data: {
    // 表单数据
    nickname: '',
    password: '',
    confirmPassword: '',
    familyCode: '',
    selectedRole: '',
    roleIndex: 0,

    // 家庭角色选项（仅前端展示使用，不影响后端role数值）
    roleOptions: [
      { name: '爸爸', value: 'father' },
      { name: '妈妈', value: 'mother' },
      { name: '儿子', value: 'son' },
      { name: '女儿', value: 'daughter' },
      { name: '爷爷', value: 'grandfather' },
      { name: '奶奶', value: 'grandmother' },
      { name: '外公', value: 'grandpa' },
      { name: '外婆', value: 'grandma' },
      { name: '其他', value: 'other' }
    ],

    // 表单验证状态
    nicknameError: '',
    passwordError: '',
    confirmPasswordError: '',
    familyCodeError: '',
    roleError: ''
  },

  onLoad(options) {
    console.log('注册页面加载');
    // 取消医生注册预选逻辑
  },

  // 输入框内容变化处理
  onNicknameInput(e) {
    this.setData({
      nickname: e.detail.value,
      nicknameError: ''
    });
  },

  onPasswordInput(e) {
    this.setData({
      password: e.detail.value,
      passwordError: ''
    });
  },

  onConfirmPasswordInput(e) {
    this.setData({
      confirmPassword: e.detail.value,
      confirmPasswordError: ''
    });
  },

  onFamilyCodeInput(e) {
    this.setData({
      familyCode: e.detail.value,
      familyCodeError: ''
    });
  },

  // 家庭角色选择处理
  onRoleChange(e) {
    const index = parseInt(e.detail.value);
    if (index >= 0 && index < this.data.roleOptions.length) {
      const selectedRole = this.data.roleOptions[index].name; // 家庭角色名称
      this.setData({
        roleIndex: index,
        selectedRole: selectedRole,
        roleError: ''
      });
    }
  },

  // 表单验证
  validateForm() {
    let isValid = true;
    const errors = {};

    // 验证账号 - 新规则：^[a-z_][a-z0-9_-]{2,31}$
    const usernameRegex = /^[a-z_][a-z0-9_-]{2,31}$/;
    if (!this.data.nickname.trim()) {
      errors.nicknameError = '请输入个人账号';
      isValid = false;
    } else if (!usernameRegex.test(this.data.nickname.trim())) {
      errors.nicknameError = '账号格式不正确：3-32位，以字母或下划线开头，可包含字母、数字、下划线、连字符';
      isValid = false;
    }

    // 验证密码
    if (!this.data.password) {
      errors.passwordError = '请输入密码';
      isValid = false;
    } else if (this.data.password.length < 6) {
      errors.passwordError = '密码至少需要6位';
      isValid = false;
    } else if (!/^(?=.*[a-zA-Z])(?=.*\d)/.test(this.data.password)) {
      errors.passwordError = '密码必须包含字母和数字';
      isValid = false;
    }

    // 验证确认密码
    if (!this.data.confirmPassword) {
      errors.confirmPasswordError = '请确认密码';
      isValid = false;
    } else if (this.data.password !== this.data.confirmPassword) {
      errors.confirmPasswordError = '两次输入的密码不一致';
      isValid = false;
    }

    // 验证家庭角色
    if (!this.data.selectedRole) {
      errors.roleError = '请选择家庭角色';
      isValid = false;
    }

    // 更新错误状态
    this.setData(errors);
    return isValid;
  },

  // 注册处理
  async onRegister() {
    if (!this.validateForm()) {
      wx.showToast({ title: '请检查输入信息', icon: 'none', duration: 2000 });
      return;
    }

    wx.showLoading({ title: '注册中...', mask: true });

    try {
      // 准备注册数据
      const registerData = {
        nickname: this.data.nickname.trim(),
        password: this.data.password,
        // 后端role固定为普通用户=1（医生注册已撤销）
        role: 1
      };

      console.log('注册数据:', registerData);

      // API调用
      const res = await reqRegisterUserData(registerData.nickname, registerData.password, registerData.role);
      console.log('注册响应:', res);

      wx.hideLoading();
      wx.showToast({ title: '注册成功', icon: 'success', duration: 2000 });

      const userInfo = {
        nickname: registerData.nickname,
        avatar: '/static/upload/default-avatar.jpg',
        hasPassword: true,
        password: registerData.password,
        phone: '',
        signature: '',
        sessionData: { username: registerData.nickname, password: registerData.password, role: registerData.role }
      };
      wx.setStorageSync('userInfo', userInfo);

      setTimeout(() => {
        wx.navigateTo({ url: '/pages/login/login' });
      }, 2000);
    } catch (error) {
      wx.hideLoading();
      console.error('注册失败:', error);
      let errorMessage = '注册失败，请重试';
      if (error && error.data) {
        errorMessage = error.data.msg || error.data.message || errorMessage;
      } else if (error && error.message) {
        errorMessage = error.message;
      }
      wx.showToast({ title: errorMessage, icon: 'none', duration: 3000 });
    }
  },

  // 跳转到登录页面
  goToLogin() {
    wx.navigateTo({ url: '/pages/login/login' });
  },

  // 清空表单
  clearForm() {
    this.setData({
      nickname: '',
      password: '',
      confirmPassword: '',
      familyCode: '',
      selectedRole: '',
      roleIndex: 0,
      nicknameError: '',
      passwordError: '',
      confirmPasswordError: '',
      familyCodeError: '',
      roleError: ''
    });
  },

  // 页面分享
  onShareAppMessage() {
    return { title: '用户注册', path: '/pages/register/register' };
  }
});
